/* eslint-disable @typescript-eslint/no-unused-vars */
/*
 * @Author: shawnxiao
 * @Date: 2021-08-15 22:28:03
 * @LastEditTime: 2021-11-15 15:38:21
 * @FilePath: /gatt-react/src/components/DynamicFormReader/FormField/SelectField.tsx
 */
import React, {useState} from 'react'
import { Form, Select } from 'antd'
const FormItem = Form.Item
const { Option } = Select
import { DebounceSelect } from './DebounceSelect'
import {jsonp} from '@/common/utils'
import request from '@/common/utils/request'

interface optionType {
  label: string;
  value: string | number;
}
interface Effect{
  fetch?: {
    action:string
    data?: any
    headers?: any
    method: string
    to?: string
    parse?: string
    jsonp?: boolean
  },
  setFieldsValue: any
}
enum modeType {
  multiple,
}
interface Props {
  config:any
  formRef:any
}

function SelectField(props:Props) {
  const { config, formRef } = props
  const {value, key, title, labelCol = {span: 10, offset: 0}, wrapperCol = {span: 24, offset: 0}, fieldKey, tooltip, rules, dataIndex, placeholder, labelInValue = true, options = [], mode, showSearch = false, allowClear = false, showArrow = false, effect, ...restProps} = config
  const [optionsDefault, setOptionsDefault] = useState([...options])
  const [defaultValue, setDefaultValue] = useState([...value])

  const handleChange = (values:any) => {
    if (effect?.setFieldsValue && Object.keys(effect?.setFieldsValue)?.length) {
      formRef?.setFieldsValue({...formRef?.getFieldsValue(), [config.key]: values, ...effect?.setFieldsValue})
    }
    setDefaultValue(values)
    console.log(values, formRef?.getFieldsValue())
  }

  const fetchData = (params:Effect['fetch']) => {
    if (params?.jsonp){
      return jsonp({
        url: params?.action as string,
        data: params?.data
      } as any)
    }
    return request({
      url: params?.action.includes('http') ? `${params?.action}` : `${process.env.APP_BASE_API}${params?.action}`,
      method: params?.method,
      model: null,
      params: {...params?.data}
    } as any)
  }
  function forMartArr (d:any[]){
    const arr:optionType[] = []
    d.forEach((item:any) => {
      arr.push({value: item[1], label: item[0]})
    })
    return arr
  }
  // 模糊搜索select框执行异步及回调
  async function fetchPolicySelect(keyWord: string): Promise<optionType[]> {
    const paramData = effect?.fetch?.data && Object.keys(effect?.fetch?.data)?.length ? {[Object.keys(effect?.fetch?.data)[0]]: keyWord} : {keyWord}
    const fetchParam = effect?.fetch ? {...effect?.fetch, data: {...paramData}} : {...paramData}
    return fetchData(fetchParam as any).then((res:any) => {
      const formatResult:Function = effect?.fetch?.parse ? eval(`(${effect?.fetch?.parse})`) : null
      const data = formatResult(res)
      const result:optionType[] = formatResult ? data.some((d:any) => Object.prototype.toString.call(d) === '[object Array]') ? forMartArr(data) : data : res?.data
      setOptionsDefault(result)
      return result
    })
  }

  return showSearch ? (
    <FormItem
      className="form-item-com-custom"
      data-index={dataIndex}
      label={title}
      tooltip={tooltip}
      name={key}
      fieldKey={fieldKey}
      key={key}
      rules={rules}
      labelCol={labelCol}
      wrapperCol={wrapperCol}>
      <DebounceSelect
        placeholder={placeholder}
        labelInValue={labelInValue}
        value={defaultValue}
        showSearch
        mode={mode}
        key={config.key}
        onChange={handleChange}
        fetchOptions={fetchPolicySelect}
        filterOption={false}
        options={optionsDefault}
        {...restProps}
      />
    </FormItem>
  ) : (
    <FormItem
      className="form-item-com-custom"
      data-index={dataIndex}
      label={title}
      tooltip={tooltip}
      name={key}
      fieldKey={fieldKey}
      key={key}
      rules={rules}
      labelCol={labelCol}
      wrapperCol={wrapperCol}>
      <Select
        placeholder={placeholder}
        labelInValue={labelInValue}
        mode={mode}
        value={defaultValue}
        key={config.key}
        onChange={handleChange}
        {...restProps}
      >
        {optionsDefault.map((d:optionType) => <Option key={d.value} value={d.value}>{d.label}</Option>)}
      </Select>
    </FormItem>
  )
}

export default SelectField
